#!usr/bin/python
# -*- coding: utf8 -*-
encoding='utf8'

import os, sys, re, codecs
from Source import Source, readFile

## Start concatenation ##

class Uncomment(object):
    def __init__(self, source):
        self.source = source

    def replaceWith(self, repl = u' '):
        comm   = False
        block  = False
        slash  = False
        bslash = False
        star   = False
        string = False
        for line in self.source.byLine():
            if comm:
                if (not block) and (not bslash):
                    # End of line-comment
                    comm = False
                slash = False
                star  = False
            nline = u''
            for c in line:
                if comm:
                    if not block:
                        # Inside line-comment
                        if bslash:
                            bslash = False
                        elif c == u'\\':
                            bslash = True
                    else:
                        # Inside block-comment
                        if c == u'*':
                            star = True
                        else:
                            if star:
                                if c == u'/':
                                    comm = False
                                    block = False
                                star = False
                    nline+= repl
                elif string:
                    if bslash:
                        bslash = False
                    elif c == u'\\':
                        bslash = True
                    elif c == string:
                        string = False
                    nline+= c
                elif slash:
                    if c == u'/':
                        comm = True
                        nline = nline[:-1] + repl*2
                    elif c == u'*':
                        comm  = True
                        block = True
                        nline = nline[:-1] + repl*2
                    else:
                        nline+= c
                    slash = False
                else:
                    if c in u'\'"':
                        string = c
                    elif c == u'/':
                        slash = True
                    nline+= c
            self.source.replaceLine(nline)
        return self.source.get()

## Stop concatenation ##

def main():
    s = Source(readFile('tests/uncomment1.cpp'))
    u = Uncomment(s)
    print u.replaceWith(u'')
    return

if __name__ == '__main__':
    main()
